<script setup>
import { ref, reactive, computed, watch } from 'vue'
import CodeBlock from '@components/CodeBlock.vue';

// 基本表单演示
const username = ref('');
const password = ref('');
const rememberMe = ref(false);

// 复杂表单演示
const formData = reactive({
  name: '',
  email: '',
  age: null,
  gender: '',
  interests: [],
  bio: '',
  agreement: false
});

// 表单验证规则
const validationRules = {
  name: (value) => !value ? '姓名不能为空' : value.length < 2 ? '姓名至少需要2个字符' : '',
  email: (value) => {
    if (!value) return '邮箱不能为空';
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return !emailRegex.test(value) ? '请输入有效的邮箱地址' : '';
  },
  age: (value) => {
    if (value === null || value === '') return '年龄不能为空';
    return isNaN(value) || value < 18 ? '年龄必须大于等于18' : '';
  },
  gender: (value) => !value ? '请选择性别' : '',
  agreement: (value) => !value ? '必须同意条款' : ''
};

// 错误状态
const errors = reactive({});

// 计算属性：表单是否有效
const isFormValid = computed(() => {
  return Object.keys(errors).length === 0 && 
         Object.values(formData).every(value => {
           if (Array.isArray(value)) return true; // 兴趣爱好可以为空
           return value !== '' && value !== null;
         }) && formData.agreement;
});

// 验证单个字段
const validateField = (field, value) => {
  if (validationRules[field]) {
    const error = validationRules[field](value);
    if (error) {
      errors[field] = error;
    } else {
      delete errors[field];
    }
  }
};

// 监听表单字段变化进行验证
watch(
  () => ({ ...formData }),
  (newData) => {
    Object.keys(newData).forEach(field => {
      validateField(field, newData[field]);
    });
  },
  { deep: true }
);

// 提交表单
const submitForm = () => {
  // 验证所有字段
  Object.keys(formData).forEach(field => {
    validateField(field, formData[field]);
  });
  
  if (isFormValid.value) {
    console.log('表单提交成功', formData);
    alert('表单提交成功！查看控制台输出的表单数据');
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (Array.isArray(formData[key])) {
      formData[key] = [];
    } else {
      formData[key] = '';
    }
  });
  formData.age = null;
  formData.agreement = false;
  Object.keys(errors).forEach(key => delete errors[key]);
};

// 处理兴趣爱好多选
const toggleInterest = (interest) => {
  const index = formData.interests.indexOf(interest);
  if (index > -1) {
    formData.interests.splice(index, 1);
  } else {
    formData.interests.push(interest);
  }
};

// 自定义组件演示 - 星级评分
const rating = ref(0);
const setRating = (value) => {
  rating.value = value;
};
</script>

<template>
  <div class="form-handling-demo">
    <h2 class="demo-title">📋 Vue 3 表单处理演示</h2>
    
    <div class="demo-grid">
      <!-- 基本表单绑定 -->
      <div class="demo-card">
        <h3 class="card-title">基本表单绑定</h3>
        <div class="demo-content">
          <form @submit.prevent class="basic-form">
            <div class="form-group">
              <label for="username">用户名:</label>
              <input 
                id="username" 
                v-model="username" 
                type="text" 
                placeholder="请输入用户名"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label for="password">密码:</label>
              <input 
                id="password" 
                v-model="password" 
                type="password" 
                placeholder="请输入密码"
                class="form-input"
              />
            </div>
            
            <div class="form-group checkbox-group">
              <input 
                id="remember-me" 
                v-model="rememberMe" 
                type="checkbox"
              />
              <label for="remember-me">记住我</label>
            </div>
            
            <div class="form-output">
              <p>用户名: {{ username }}</p>
              <p>密码: {{ password }}</p>
              <p>记住我: {{ rememberMe ? '是' : '否' }}</p>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 复杂表单验证 -->
      <div class="demo-card">
        <h3 class="card-title">复杂表单与验证</h3>
        <div class="demo-content">
          <form @submit.prevent="submitForm" class="complex-form">
            <div class="form-group">
              <label for="name">姓名 *:</label>
              <input 
                id="name" 
                v-model="formData.name" 
                type="text" 
                :class="['form-input', { 'error': errors.name }]"
              />
              <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
            </div>
            
            <div class="form-group">
              <label for="email">邮箱 *:</label>
              <input 
                id="email" 
                v-model="formData.email" 
                type="email" 
                :class="['form-input', { 'error': errors.email }]"
              />
              <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
            </div>
            
            <div class="form-group">
              <label for="age">年龄 *:</label>
              <input 
                id="age" 
                v-model.number="formData.age" 
                type="number" 
                min="0" 
                :class="['form-input', { 'error': errors.age }]"
              />
              <span v-if="errors.age" class="error-message">{{ errors.age }}</span>
            </div>
            
            <div class="form-group">
              <label>性别 *:</label>
              <div class="radio-group">
                <label>
                  <input 
                    v-model="formData.gender" 
                    type="radio" 
                    value="male"
                  />
                  男
                </label>
                <label>
                  <input 
                    v-model="formData.gender" 
                    type="radio" 
                    value="female"
                  />
                  女
                </label>
              </div>
              <span v-if="errors.gender" class="error-message">{{ errors.gender }}</span>
            </div>
            
            <div class="form-group">
              <label>兴趣爱好:</label>
              <div class="checkboxes-group">
                <label v-for="interest in ['阅读', '运动', '音乐', '编程']" :key="interest">
                  <input 
                    type="checkbox" 
                    :value="interest" 
                    :checked="formData.interests.includes(interest)"
                    @change="toggleInterest(interest)"
                  />
                  {{ interest }}
                </label>
              </div>
            </div>
            
            <div class="form-group">
              <label for="bio">个人简介:</label>
              <textarea 
                id="bio" 
                v-model="formData.bio" 
                rows="3" 
                class="form-input"
              ></textarea>
            </div>
            
            <div class="form-group checkbox-group">
              <input 
                id="agreement" 
                v-model="formData.agreement" 
                type="checkbox"
              />
              <label for="agreement">我同意所有条款 *</label>
              <span v-if="errors.agreement" class="error-message">{{ errors.agreement }}</span>
            </div>
            
            <div class="form-actions">
              <button type="button" @click="resetForm" class="btn-reset">重置</button>
              <button type="submit" :disabled="!isFormValid" class="btn-submit">提交</button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 自定义表单组件 -->
      <div class="demo-card">
        <h3 class="card-title">自定义表单组件</h3>
        <div class="demo-content">
          <div class="rating-component">
            <h4>星级评分:</h4>
            <div class="rating-stars">
              <span 
                v-for="n in 5" 
                :key="n" 
                class="star"
                :class="{ active: rating >= n }"
                @click="setRating(n)"
              >
                ★
              </span>
            </div>
            <p class="rating-value">当前评分: {{ rating }}</p>
          </div>
          
          <div class="code-snippet">
            <CodeBlock code="<!-- 自定义评分组件实现思路 -->" language="html"></CodeBlock>
          </div>
        </div>
      </div>
      
      <!-- 表单提交状态 -->
      <div class="demo-card">
        <h3 class="card-title">表单最佳实践</h3>
        <div class="demo-content">
          <ul class="best-practices-list">
            <li><strong>响应式表单绑定:</strong> 使用 v-model 实现表单和数据的双向绑定</li>
            <li><strong>表单验证:</strong> 实时验证用户输入，提供清晰的错误提示</li>
            <li><strong>无障碍支持:</strong> 正确使用 label、aria 属性等确保表单可访问性</li>
            <li><strong>防抖处理:</strong> 对输入验证使用防抖提高性能</li>
            <li><strong>提交状态管理:</strong> 处理加载状态、成功/失败反馈</li>
            <li><strong>表单重置:</strong> 提供清晰的重置功能</li>
            <li><strong>自定义组件:</strong> 使用 v-model 构建可重用的表单组件</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.form-handling-demo {
  padding: 20px;
}

.demo-title {
  text-align: center;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.demo-card {
  background: white; /* 浅色主题下为白色背景 */
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 深色主题下的样式 */
[data-theme="dark"] .demo-card {
  background: #000000; /* 深色主题下为黑色背景 */
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  color: #ffffff;
}

.card-title {
  color: #667eea;
  margin-bottom: 15px;
}

.demo-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 表单样式 */
.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.form-input.error {
  border-color: #ff6b6b;
}

.error-message {
  display: block;
  color: #ff6b6b;
  font-size: 12px;
  margin-top: 5px;
}

/* 复选框和单选框组 */
.checkbox-group, .radio-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.checkbox-group input, .radio-group input {
  margin-right: 5px;
}

.checkboxes-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

/* 表单按钮 */
.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.btn-submit, .btn-reset {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-submit {
  background-color: #667eea;
  color: white;
}

.btn-submit:hover:not(:disabled) {
  background-color: #764ba2;
}

.btn-submit:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-reset {
  background-color: #f5f5f5;
  color: #333;
}

.btn-reset:hover {
  background-color: #e0e0e0;
}

/* 表单输出区域 */
.form-output {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
}

.form-output p {
  margin: 5px 0;
  font-family: monospace;
}

/* 评分组件 */
.rating-component {
  text-align: center;
}

.rating-stars {
  font-size: 30px;
  cursor: pointer;
  margin: 15px 0;
}

.star {
  color: #ddd;
  transition: color 0.2s;
}

.star:hover,
.star.active {
  color: #f1c40f;
}

.rating-value {
  font-weight: bold;
  color: #667eea;
}

/* 最佳实践列表 */
.best-practices-list {
  padding-left: 20px;
}

.best-practices-list li {
  margin-bottom: 8px;
  color: #555;
}

/* 代码片段样式 */
.code-snippet {
  background-color: #f5f5f5;
  border-radius: 5px;
  padding: 10px;
  overflow-x: auto;
}

.code-snippet pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
  color: #333;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .demo-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .checkboxes-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>